const parse_base_value = (new_view: any, startPosition: any) => {
  const _sei = {
    hor: new_view.getInt32(startPosition) / 1000000,
    ver: new_view.getInt32(startPosition + 4) / 1000000 == 0 ? -0.0 : new_view.getInt32(startPosition + 4) / 1000000,
    fieldHor: new_view.getUint16(startPosition + 8) / 100, //
    focus: new_view.getUint16(startPosition + 10) //
  }
  return _sei
}

const parse_alarm_value = (new_view: any, startPosition: any, sei: any) => {
  sei.sei_ver = new_view.getUint8(startPosition)
  sei.fire_count = new_view.getUint8(startPosition + 1)
  if (sei.fire_count != 0) {
    const alarm = {
      //告警像素x
      x: new_view.getInt16(startPosition + 2),
      //告警像素y
      y: new_view.getInt16(startPosition + 4),
      //框左上角x
      lx: new_view.getInt16(startPosition + 6),
      //框左上角y
      ly: new_view.getInt16(startPosition + 8),
      //宽
      w: new_view.getInt16(startPosition + 10),
      //高
      h: new_view.getInt16(startPosition + 12),
      //置信度
      cd: new_view.getInt32(startPosition + 14) / 10000,
      //对比度
      ct: new_view.getInt32(startPosition + 18) / 10000
    }
    sei.alarm = alarm
  }
  return sei
}

const filterSEI03 = (view: any, len: number) => {
  const new_view = new DataView(new ArrayBuffer(view.byteLength))
  let j = 0
  for (let i = 0; i < len; i++) {
    if (i >= 25) {
      const a = view.getInt8(i - 2)
      const b = view.getInt8(i - 1)
      const c = view.getInt8(i)

      if (a == 0 && b == 0 && c == 3) {
        continue
      }
    }
    new_view.setInt8(j, view.getInt8(i))
    j++
  }
  return new_view
}

export const parseSEI = (view: any) => {
  if (view.byteLength >= 48) {
    const arrayBuff = new DataView(view)
    //h264
    if (arrayBuff.getInt8(20) == 6) {
      const new_view = filterSEI03(arrayBuff, view.byteLength > 48 ? 100 : 48)
      let _sei = parse_base_value(new_view, 23)
      //新sei新增了告警
      if (arrayBuff.getUint8(22) > 14) {
        _sei = parse_alarm_value(new_view, 39, _sei)
      }
      return _sei
    }
    //h265
    if (arrayBuff.getInt8(20) == 78 && arrayBuff.getInt8(22) == 5) {
      const new_view = filterSEI03(arrayBuff, view.byteLength > 48 ? 100 : 48)
      let _sei = parse_base_value(new_view, 24)
      if (arrayBuff.getUint8(23) > 14) {
        //新sei
        _sei = parse_alarm_value(new_view, 40, _sei)
      }
      return _sei
    }
  }
}
